/**
 * Ant Design Pro v4 use `@ant-design/pro-layout` to handle Layout.
 *
 * @see You can view component api by: https://github.com/ant-design/ant-design-pro-layout
 */
import type {
  MenuDataItem,
  BasicLayoutProps as ProLayoutProps,
  Settings,
} from '@ant-design/pro-layout';
import ProLayout, { DefaultFooter } from '@ant-design/pro-layout';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import type { Dispatch } from 'umi';
import { Link, useIntl, connect, history } from 'umi';
// import { GithubOutlined } from '@ant-design/icons';
import { Result, Button } from 'antd';
import Authorized from '@/utils/Authorized';
import RightContent from '@/components/GlobalHeader/RightContent';
import type { ConnectState } from '@/models/connect';
import { getMatchMenu } from '@umijs/route-utils';
import logo from '../assets/logo.svg';
import { getTreeList } from '../pages/system/menu/service';

const noMatch = (
  <Result
    status={403}
    title="403"
    subTitle="Sorry, you are not authorized to access this page."
    extra={
      <Button type="primary">
        <Link to="/user/login">Go Login</Link>
      </Button>
    }
  />
);
export type BasicLayoutProps = {
  breadcrumbNameMap: Record<string, MenuDataItem>;
  route: ProLayoutProps['route'] & {
    authority: string[];
  };
  settings: Settings;
  dispatch: Dispatch;
} & ProLayoutProps;

export type BasicLayoutContext = { [K in 'location']: BasicLayoutProps[K] } & {
  breadcrumbNameMap: Record<string, MenuDataItem>;
};
/** Use Authorized check all menu item */

const menuDataRender = (menuList: MenuDataItem[]): MenuDataItem[] =>
  menuList.map((item) => {
    const localItem = {
      ...item,
      children: item.children ? menuDataRender(item.children) : undefined,
    };
    return Authorized.check(item.authority, localItem, null) as MenuDataItem;
  });

const defaultFooterDom = (
  <DefaultFooter
    copyright={`${new Date().getFullYear()} 青锋后台管理系统`}
    links={[
      {
        key: '青锋官网',
        title: '青锋官网',
        href: 'https://xinlingge.cn:8181',
        blankTarget: true,
      },
      // {
      //   key: 'github',
      //   title: <GithubOutlined />,
      //   href: 'https://github.com/ant-design/ant-design-pro',
      //   blankTarget: true,
      // },
      {
        key: '在线预览',
        title: '在线预览',
        href: 'https://xinlingge.cn:8181/qingfeng',
        blankTarget: true,
      },
    ]}
  />
);

const BasicLayout: React.FC<BasicLayoutProps> = (props) => {
  const {
    dispatch,
    children,
    settings,
    location = {
      pathname: '/',
    },
  } = props;

  const menuDataRef = useRef<MenuDataItem[]>([]);
  

  const mData = [
    {
      "path": "/dashboard",
      "name": "dashboard",
      "icon": "dashboard",
      "children": [
        {
          "path": "/dashboard/analysis",
          "name": "analysis"
        },
        {
          "path": "/dashboard/monitor",
          "name": "monitor"
        },
        {
          "path": "/dashboard/workplace",
          "name": "workplace"
        }
      ]
    }
  ]
  const [menuData, setMenuData] = useState<MenuDataItem[]>([]);
  // useEffect(() => {
  //   console.log('0000000000000000000000')
  //   console.log(menuData)
  // }, [menuData]);

  const menuAuthorized = (menuList: MenuDataItem[]): MenuDataItem[] =>
  menuList.map((item) => {
    const localItem = {
      ...item,
      children: item.children ? menuAuthorized(item.children) : undefined,
    };
    return Authorized.check(item.authority, localItem, null) as MenuDataItem;
  });

  useEffect(() => {
    console.log('1111111111111111111111')
    console.log(menuData)
    // setMenuData(mData);
    //查询菜单
    getTreeList({types: '0,1,3,4'}).then((res:any) =>{
      // console.log('--------------我进来查询菜单了。。。。')
      // console.log(res);
      const treeData = fommat(
        res.data,
        "parent_id"
      );
      const menu = menuAuthorized(treeData);
      console.log(menu);
      setMenuData(menu);
      console.log('333333333333333333333')
      console.log(menu);
    })

    // getTreeList({ types: '0,1,3,4' }).then((response) => {
    //   const treeData = fommat({
    //     arrayList: response.data.data,
    //     pidStr: "parent_id",
    //   });
    //   const accessedRouters = filterAsyncRouter(treeData, roles)
    //   const finalRouters = filterEmptyDirectory(accessedRouters)
    //   console.log("==================")
    //   console.log(finalRouters)
    //   commit('SET_ROUTERS', finalRouters)
    //   resolve()
    // });

    // fetch('/api/example.json')
    // .then(response => response.json())
    // .then(data => {
    //   setMenuData(data || []);
    // });

    if (dispatch) {
      dispatch({
        type: 'user/fetchCurrent',
      });
    }
  }, []);
  const fommat =  (arrayList:any,pidStr = "parent_id",idStr = "id",childrenStr = "children") => {
    let listOjb = {}; // 用来储存{key: obj}格式的对象
    let treeList = []; // 用来储存最终树形结构数据的数组
    // 将数据变换成{key: obj}格式，方便下面处理数据
    // const responseDataLength = response?.data?.data?.length || 0;
    for (let i = 0; i < arrayList?.length || 0; i++) {
      var data = arrayList[i];
      data.key = data.id;
      data.icon = "";
      //处理菜单格式信息
      // if (data.type == '0') {//目录
      // } else if (data.type == '1') {
      // } else if (data.type == '4') {
      // }
      const authority = data.role_ids?.split(',')
      if (data.child_num > 0) {
        if (authority == undefined) {
          authority = ['system']
        } else {
          authority.push('system');
        }
      }
      data.authority = authority;
      if (data.type == '3') {
        data.target = '_black';
      }
      // console.log(data.meta)
      listOjb[arrayList[i][idStr]] = data;
    }
    // 根据pid来将数据进行格式化
    for (let j = 0; j < arrayList?.length || 0; j++) {
      // 判断父级是否存在
      let haveParent = listOjb[arrayList[j][pidStr]];
      if (haveParent) {
        // 如果有没有父级children字段，就创建一个children字段
        !haveParent[childrenStr] && (haveParent[childrenStr] = []);
        // 在父级里插入子项
        haveParent[childrenStr].push(arrayList[j]);
      } else {
        // 如果没有父级直接插入到最外层
        treeList.push(arrayList[j]);
      }
    }
    return treeList;
  }
  /** Init variables */

  const handleMenuCollapse = (payload: boolean): void => {
    if (dispatch) {
      dispatch({
        type: 'global/changeLayoutCollapsed',
        payload,
      });
    }
  };
  // get children authority
  const authorized = useMemo(
    () =>
      getMatchMenu(location.pathname || '/', menuDataRef.current).pop() || {
        authority: undefined,
      },
    [location.pathname],
  );

  const { formatMessage } = useIntl();

  return menuData && menuData.length>0 ?(
    <ProLayout
      logo={logo}
      formatMessage={formatMessage}
      {...props}
      {...settings}
      onCollapse={handleMenuCollapse}
      onMenuHeaderClick={() => history.push('/')}
      menuItemRender={(menuItemProps, defaultDom) => {
        if (
          menuItemProps.isUrl ||
          !menuItemProps.path ||
          location.pathname === menuItemProps.path
        ) {
          return defaultDom;
        }
        return <Link to={menuItemProps.path}>{defaultDom}</Link>;
      }}
      breadcrumbRender={(routers = []) => [
        {
          path: '/',
          breadcrumbName: formatMessage({ id: 'menu.home' }),
        },
        ...routers,
      ]}
      itemRender={(route, params, routes, paths) => {
        const first = routes.indexOf(route) === 0;
        return first ? (
          <Link to={paths.join('/')}>{route.breadcrumbName}</Link>
        ) : (
          <span>{route.breadcrumbName}</span>
        );
      }}
      footerRender={() => {
        if (settings.footerRender || settings.footerRender === undefined) {
          return defaultFooterDom;
        }
        return null;
      }}
      menuDataRender={() => menuData}
      // menuRender={false}
      rightContentRender={() => <RightContent />}
      postMenuData={(menuData) => {
        menuDataRef.current = menuData || [];
        return menuData || [];
      }}
      waterMarkProps={{
        content: '青锋系统',
        fontColor: 'rgba(24,144,255,0.15)',
      }}
    >
      <Authorized authority={authorized!.authority} noMatch={noMatch}>
        {children}
      </Authorized>
    </ProLayout>
  ) : (
    <span>
     
    </span>
  );
};

export default connect(({ global, settings }: ConnectState) => ({
  collapsed: global.collapsed,
  settings,
}))(BasicLayout);
